package com.yc.votesys.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yc.votesys.util.StringUtil;


/**
 * 过滤后台
 * @author UNO
 * @date 2021年7月31日
 * Email 2759451734@qq.com
 */
@WebFilter("/front/*")
public class CheckFrontFilter implements Filter {
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//判断用户有没有登录 -> 如果登录 我们就将登录的信息存到session中
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		
		//判断是否登录 session是否有值
		if( req.getSession().getAttribute("currentLoginUser") == null){
			//未登录 跳转到指定姐卖你
			resp.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			
			//重定向 resp.sendRedirect(errorPage);  死循环
			//2、演示2 b 想办法获取的URL地址 -> 获取的URL地址 + 资源路径
			String basePath = req.getScheme() + ".//" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/";
			out.print("<script>alert('请先登录...');location.href='" + basePath +"login.html';<script>");
			out.flush();//刷新缓冲区
			out.close();//会默认关闭流 可以省略
			return;
		}
		
		String path = req.getRequestURI();
		String projectName = req.getContextPath();
		path = path.replaceFirst(projectName, "");
		
		//内部转发
		req.getRequestDispatcher("../WEB-INF/" + path).forward(req, resp);
	}
}
